package cn.tannn.ops.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DomainExtractor {
    private static final String DOMAIN_REGEX = "^(?:https?:\\/\\/)?(?:[^@\\/\\n]+@)?(?:www\\.)?([^:\\/\\n]+)";
    private static final Pattern DOMAIN_PATTERN = Pattern.compile(DOMAIN_REGEX);

    public static class DomainInfo {
        // 是否为子域名、
        public boolean isSubdomain;
        // 子域名（如果存在）
        public String subdomain;
        // 主域名
        public String mainDomain;

        @Override
        public String toString() {
            return "DomainInfo{" +
                    "isSubdomain=" + isSubdomain +
                    ", subdomain='" + subdomain + '\'' +
                    ", mainDomain='" + mainDomain + '\'' +
                    '}';
        }
    }

    public static DomainInfo extractDomainInfo(String url) {
        DomainInfo info = new DomainInfo();
        Matcher matcher = DOMAIN_PATTERN.matcher(url);

        if (matcher.find()) {
            String domain = matcher.group(1);
            String[] parts = domain.split("\\.");

            if (parts.length > 2) {
                info.isSubdomain = true;
                info.subdomain = domain;
                info.mainDomain = parts[parts.length - 2] + "." + parts[parts.length - 1];
            } else {
                info.isSubdomain = false;
                info.mainDomain = domain;
            }
        }

        return info;
    }
}
